//
//  StatisticsController.m
//  PropertyMananger
//
//  Created by bh on 17/1/13.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "StatisticsController.h"
#import "StatisticsCell.h"
#import "StatisticHeaderView.h"
#import "MarqueeController.h"
#import "StasticsHeader.h"
#import "JhtMarqueeLabel.h"
#import "WHBKPieView.h"
#import "SelectedMonthView.h"
#import "StatisticsModel.h"
#import "TimerSelectedView.h"

@interface StatisticsController ()<UIGestureRecognizerDelegate,SelectedMonthViewDelegate>
{
    // 跑马灯
    JhtMarqueeLabel *_marquee;
    WHBKPieView * _pieView;
}
@property (nonatomic,strong) SelectedMonthView * selectedView;
@property (nonatomic,strong) StasticsHeader * tableHeaderView;
@property (nonatomic,assign) NSInteger  selectedMonth;//选择月份

@property (nonatomic,strong)  NSDateComponents* comp;//系统的时间
@property (nonatomic,copy) NSString * timeStr;//系统默认的时间

//@property (nonatomic,copy) NSString * yearStr;//年份
//@property (nonatomic,copy) NSString * monthStr;//月份
//@property (nonatomic,copy) NSString * monthData;//提交的年月

//@property (nonatomic,assign) int item;//保存的月份

@property (nonatomic,strong) NSArray * timeArr;

@end

@implementation StatisticsController
static NSString * const headerID = @"headerID";

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // 开启跑马灯
    [_marquee marqueeOfSettingWithState:MarqueeStart];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    // 关闭跑马灯
    [_marquee marqueeOfSettingWithState:MarqueeShutDown];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTitleViewName:@"统计"];
    
    //获取年月日
    [self getYearData];
    
    [self getYearAndMonthData];
    
   //工单明细列表
    [self setTableView];
    
    // 添加跑马灯
    [self labsCreateMarquee];
    
    //暂未图
    [self createPlaceHolder];
    
    //统计列表数据
    [self postStasticsData];
    
     //刷新UI
 //   [self createRefresh];
}
#pragma mark - 创建列表
- (void)setTableView{

    if (iOS7 >7.0) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    if (iOS7 < 7.0) {
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 50, BHscreenW, BHscreenH - 64 - 50) isGroup:NO];
    self.tableView.showsVerticalScrollIndicator = NO;
    //注册
    [self.tableView registerClass:[StatisticHeaderView class] forHeaderFooterViewReuseIdentifier:headerID];
    
    self.tableHeaderView = [[StasticsHeader alloc]initWithFrame:CGRectMake(0, 50, BHscreenW, 260)];
    
    _pieView = [[WHBKPieView alloc]initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width,200)];


 //   self.workNum = 160;
    //获取工单数量的通知
    NSDictionary * dict = @{@"key":[NSString stringWithFormat:@"%ld", self.workNum]};
    [[NSNotificationCenter defaultCenter] postNotificationName:workNumNoticeCenter object:nil userInfo:dict];
    
    [self.tableHeaderView addSubview:_pieView];
    
    //点击选择月份
    [self.tableHeaderView.monthButton addTarget:self action:@selector(selectedMonth:) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.tableHeaderView = self.tableHeaderView;
    
    //初始化各种报修单数据源
    self.repairArray = [[NSMutableArray alloc]init];
    self.repairListArray = [[NSMutableArray alloc]init];

}
#pragma mark - 创建刷新UI
- (void)createRefresh{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.nextPage = 1;
        
        self.isDown = YES;
        //获取数据
        // [self postOwnerInfoData];
        
    }];
    
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.nextPage += 1;
        
        self.isDown = NO;
        //获取数据
        //  [self postOwnerInfoData];
        
        //    [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }];
}
#pragma makr - 点击选择月份
- (void)selectedMonth:(UIButton *)button
{
    DLog(@"点击选择月份");
//    self.selectedView = [[SelectedMonthView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 270)/2, self.view.frame.size.height/2-80, 270, 210)];
//    [self.view addSubview:self.selectedView];
//    
//    self.selectedView.delegate = self;
//    
//    [self.selectedView selectedMonthView];

    __block StatisticsController *weakSelf = self;
    dateTimePickerView = [[HcdDateTimePickerView alloc] initWithDatePickerMode:DatePickerYearMonthMode defaultDateTime:[[NSDate alloc]initWithTimeIntervalSinceNow:1000]];
    [self.view addSubview:dateTimePickerView];
    
    dateTimePickerView.topViewColor = BHGrayColor;
    dateTimePickerView.buttonTitleColor = Theme_Color;
    
    dateTimePickerView.clickedOkBtn = ^(NSString * datetimeStr){
        NSLog(@"%@", datetimeStr);
      //  weakSelf.tableHeaderView.yearLabel.text = [NSString stringWithFormat:@"%@",datetimeStr];
        
        NSArray * monthArray = [datetimeStr componentsSeparatedByString:@"-"];
        DLog(@"月份 == %@",monthArray[1]);
        
        if ([monthArray[1]integerValue] <=9) {
            
            weakSelf.tableHeaderView.yearLabel.text = [NSString stringWithFormat:@"%@年/0%@月",monthArray[0],monthArray[1]];
             weakSelf.timeStr = [NSString stringWithFormat:@"%@-0%@",monthArray[0],monthArray[1]];
        }else{
        
        weakSelf.tableHeaderView.yearLabel.text = [NSString stringWithFormat:@"%@年/%@月",monthArray[0],monthArray[1]];
            
        weakSelf.timeStr = [NSString stringWithFormat:@"%@-%@",monthArray[0],monthArray[1]];
        }
        
        weakSelf.isDown = YES;
        [weakSelf postStasticsData];
    };
    
    if (dateTimePickerView) {
        [self.view addSubview:dateTimePickerView];
        [dateTimePickerView showHcdDateTimePicker];
    }

    
}
- (void)didSelectMonth:(NSInteger)num{
    NSLog(@"点击了 == %ld",(long)num);
 //   self.tableHeaderView.yearLabel.text = [NSString stringWithFormat:@"%ld年/%ld月份",self.comp.year,num + 1];
    self.selectedMonth = num;
  
    //    if (num == 12) {
//        
//         self.tableHeaderView.yearLabel.text = [NSString stringWithFormat:@"2017年/全年"];
//    }else{
//    self.tableHeaderView.yearLabel.text = [NSString stringWithFormat:@"2017年/%ld月份",num + 1];
//    }
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSString stringWithFormat:@"%ld",self.selectedMonth] forKey:@"month"];
    [userDefaults synchronize];
    
    
    [self.tableView reloadData];
    
    [self postStasticsData];
    

}
#pragma mark - 添加跑马灯
- (void)labsCreateMarquee {
    _marquee = [[JhtMarqueeLabel alloc] initWithFrame:CGRectMake(0, 0, BHscreenW, 50) withSingleScrollDuration:20.0];
    _marquee.textColor = BHColor(102, 102, 102);
    DLog(@"%@",_marquee.text);
    
    //    _marquee.backgroundColor = [UIColor redColor];
    [self.view addSubview:_marquee];
    
    // 给跑马灯添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labsMarqueeTapGes:)];
    [_marquee addGestureRecognizer:tap];
}

- (void)labsMarqueeTapGes:(UITapGestureRecognizer *)ges {
    NSLog(@"点击跑马灯啦啊！！！");
    
    // [self.navigationController pushViewController:[[MarqueeController alloc] init] animated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.repairListArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    StatisticsCell * cell = [StatisticsCell cellWithTableView:tableView];
    ListDetail * model = self.repairListArray[indexPath.row];
    cell.model = model;
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    StatisticHeaderView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
 
    
        self.timeArr = [self.timeStr componentsSeparatedByString:@"-"];
        headerView.headerTitleLabel.text = [NSString stringWithFormat:@"%@月工单明细", self.timeArr[1]];
        
        self.tableHeaderView.yearLabel.text = [NSString stringWithFormat:@"%@年/%@月份",self.timeArr[0],self.timeArr[1]];
        
        self.titleLabel.text = [NSString stringWithFormat:@"暂无%@月份工单",self.timeArr[1]];
  
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

#pragma mark - 统计数据请求
- (void)postStasticsData
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"努力加载数据中...";
    // 隐藏时从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.userInteractionEnabled = YES;
   
    NSDictionary * parms = nil;
    
        parms =  @{
                   @"CommunityID":userModel.CommunityID,
                   @"Date":self.timeStr,
                   @"json":@"\{\"jsonEntity\":\{},\"action\":\"statistics\",\"version\":\"V1.0\"}"
                   };
    
    DLog(@"提交的参数 === %@",parms);
    [WorkOrderRequest postStaticsSuccess:^(id data) {
        [self.repairListArray removeAllObjects];
         [MBProgressHUD hideHUDForView:self.view];
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"统计列表的数据 == %@",dict1);
        
        NSArray * array = dict1[@"ListDetail"];
        if ([array isKindOfClass:[NSNull class]]) {
            
        }else{
            
            for (NSDictionary * dict in array) {
                ListDetail * model = [[ListDetail alloc]init];
                [model setValuesForKeysWithDictionary:dict];
                [self.repairListArray addObject:model];
            }
        }
        
        if (self.repairListArray.count == 0) {
            
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        }else{
        
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;

        }
        
         StatisticsModel * model = [[StatisticsModel alloc]init];
        [model setValuesForKeysWithDictionary:dict1];
        
        //总的数量
//        NSInteger commonCount = [[NSString stringWithFormat:@"%@",model.Repaircommon] integerValue];
//        NSInteger singleCount = [[NSString stringWithFormat:@"%@",model.Repairsingle] integerValue];
//        NSInteger complainCount = [[NSString stringWithFormat:@"%@",model.Complainall] integerValue];
        
//        self.workNum = commonCount + singleCount + complainCount;
        self.workNum = [[NSString stringWithFormat:@"%@",model.all]integerValue];
        
     _marquee.text = [NSString stringWithFormat:@"  %ld年工单总数: %ld 单； 公共报修: %@ 单； 个人报修: %@ 单；" @"投诉单: %@ 单；",self.comp.year,self.workNum ,model.Repaircommon,model.Repairsingle,model.Complainall];
      
       _pieView.dataResource = @[model.Complainall ,model.Repaircommon,model.Repairsingle];
        DLog(@"==== %@",_pieView.dataResource);
        if ([model.Complainall isEqualToString:@"0"] && [model.Repaircommon isEqualToString:@"0"] && [model.Repairsingle isEqualToString:@"0"]) {
            
            DLog(@"工单数为0");
            
        }
        
        _pieView.pieChartView.titleLabel.text = [NSString stringWithFormat:@"%ld", self.workNum];
        
        self.titleStr = _pieView.pieChartView.titleLabel.text;
        self.pingjieStr = [NSString stringWithFormat:@"%@",self.titleStr];
        
        self.stra = [[NSMutableAttributedString alloc]initWithString:self.pingjieStr];//可随意拼接字符串
        [self.stra addAttributes:@{NSFontAttributeName:BHFont(20),NSForegroundColorAttributeName:BHColor(51, 51, 51)} range:NSMakeRange(0, self.titleStr.length)];
        _pieView.pieChartView.titleLabel.attributedText = self.stra;
        
        [self.tableView reloadData];
        
    } Fail:^(NSString *errorDes) {

        [MBProgressHUD hideHUD];
    } param:parms];


}
- (void)getYearData{

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    self.comp = [gregorian components: unitFlags fromDate:dt];

}
#pragma mark - 暂未图
- (void)createPlaceHolder
{
    self.placehoderImg = [[UIImageView alloc]init];
    [self.tableView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_work_order"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.tableView.mas_bottom).with.offset(100 + 230);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.tableView addSubview:self.titleLabel];
    self.titleLabel.text = [NSString stringWithFormat:@"暂无%@月份工单明细",self.timeArr[1]];
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(150, 25));
    }];
    
}
#pragma mark - 获取系统时间
- (void)getYearAndMonthData{
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSTimeInterval time = [zone secondsFromGMTForDate:date];
    NSDate *dateNow = [date dateByAddingTimeInterval:time];
    NSString * timeDataStr = [NSString stringWithFormat:@"%@",dateNow];
    DLog(@" === %@",dateNow);
    
    NSArray * arr = [timeDataStr componentsSeparatedByString:@"+"];
    DLog(@"日期格式化 == %@",arr[0]);
    
    NSArray * timeArr = [timeDataStr componentsSeparatedByString:@"-"];
    NSString * timeStr = [NSString stringWithFormat:@"%@-%@",timeArr[0],timeArr[1]];
    DLog(@"拼接好的时间===%@",timeStr);
    self.timeStr = timeStr;    
}
@end
